﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace OfficeExport
{
    /// <summary>
    /// Identifies the non-generic exporter base class.
    /// </summary>
    public abstract class ExporterBase
    {
        /// <summary>
        /// Gets the preferred file extension for the current export format.
        /// </summary>
        /// <value>The preferred file extension.</value>
        public abstract string PreferredFileExtension { get; }
        /// <summary>
        /// Exports the specified document.
        /// </summary>
        /// <param name="sourcePath">The source path.</param>
        /// <param name="targetPath">The target path.</param>
        public void Export(string sourcePath, string targetPath)
        {
            if (!File.Exists(sourcePath)) {
                throw new FileNotFoundException("Specified source document does not exist");
            }

            try {
                OnExport(sourcePath, targetPath);
            }
            finally {
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }

        /// <summary>
        /// Implements the actual export logic.
        /// </summary>
        /// <param name="sourcePath">The source path.</param>
        /// <param name="targetPath">The target path.</param>
        protected abstract void OnExport(string sourcePath, string targetPath);

        /// <summary>
        /// Gets the exporter for given file name.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <returns></returns>
        public static ExporterBase GetExporterForFile(string fileName)
        {
            var extension = Path.GetExtension(fileName).ToLowerInvariant();
            if (extension == ".doc" || extension == ".docx") {
                return new WordExporter();
            }
            if (extension == ".ppt" || extension == ".pptx") {
                return new PowerPointExporter();
            }
            if (extension == ".xls" || extension == ".xlsx") {
                return new ExcelExporter();
            }
            return null;
        }
    }
}
